package com.lyssoft.learning;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.String;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

public class EchoSSLServer {
    public static void main(String... args) throws Exception {
        String keystorePath = "src/main/resources/cert.jks";
        String keystorePass = "123456";
        String keyPass      = "123456";
        
        AtomicBoolean shouldExit = new AtomicBoolean(false);
        
        // 初始化密钥库
        KeyStore keystore = KeyStore.getInstance("jks");
        try (InputStream ksStream = new FileInputStream(new File(keystorePath))) {
            keystore.load(ksStream, keystorePass.toCharArray());
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
        kmf.init(keystore, keyPass.toCharArray());
        
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, null);
        
        ServerSocket serverSocket = sslContext.getServerSocketFactory().createServerSocket();
        serverSocket.bind(new InetSocketAddress("0.0.0.0", 8443));
        System.out.println("SSL Listening on 8443");
        
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                shouldExit.set(true);
            }
        });
        
        while (!shouldExit.get()) {
            Socket client = serverSocket.accept();
            
            System.out.println("New Client: " + client.getRemoteSocketAddress().toString());
            try (Scanner scanner = new Scanner(client.getInputStream(), "UTF-8")) {
                String line = null;
                
                try {
                    while ((line = scanner.nextLine()) != null && !shouldExit.get()) {
                        System.out.println(line);
                    }
                } catch (Exception e) {
                    
                }
            }
            
            client.close();
            
            System.out.println("Client Closed: " + client.getRemoteSocketAddress().toString());
        }
        
        serverSocket.close();
    }
}